<template>
	<!-- #ifdef H5||APP-PLUS -->
	<view class="c-scratch-card" :scratchCardData="scratchCardData" :change:scratchCardData="scratchCard.render" :style="{width,height}" >
		<div class="canvas" :id='myCanvasId'></div>
		<slot v-if="isShowPrizeName">
			<view class="prizeName">
				{{ prizeName }}
			</view>
		</slot>
	</view>
	<!-- #endif -->
	<!-- #ifdef MP -->
	<view class="c-scratch-card" :style="{ width, height }">
		<canvas
		disable-scroll="true"
			@touchstart="ontouchstart"
			@touchmove="ontouchmove"
			@touchend="ontouchend"
			class="canvas"
			:id="myCanvasId"
			type="2d"
		></canvas>
		<slot v-if="isShowPrizeName">
			<view class="prizeName">
				{{ prizeName }}
			</view>
		</slot>
	</view>
	<!-- #endif -->
</template>
<script>
/**
 * c-scratch-card 刮刮卡
 * @description 刮刮卡
 * @property {String} canvasId 画布id
 * @property {Number} lineWidth 画笔宽度 默认 20
 * @property {String} width 图像宽度 默认750rpx 单位rpx/px
 * @property {String} height 图像高度 默认750rpx 单位rpx/px
 * @property {String} text 涂层上的文字 默认“刮刮卡” 设置图层图片时失效
 * @property {Number} textSize 涂层上的文字的大小 默认“24” 设置图层图片时失效
 * @property {String} textColor 涂层上的文字的颜色 默认“#ffffff” 设置图层图片时失效
 * @property {String} bgColor 涂层颜色 默认“#666666” 设置图层图片时失效
 * @property {String} bgSrc 涂层图片地址
 * @property {Boolean} disabled 是否禁止刮开涂层 默认 false
 * @property {String} prizeName 奖品名称 可通过插槽替换该区域
 */
import uuid from './js/uuid.js';
export default {
	props: {
		canvasId: {
			type: String,
		},
		width: {
			type: String,
			default: '750rpx',
		},
		height: {
			type: String,
			default: '750rpx',
		},
		lineWidth:{ //画笔宽度
			type: Number,
			default: 20
		},
		text: {
			type: String,
			default: '刮刮卡',
		},
		textSize: {
			type: Number,
			default: 24,
		},
		textColor: {
			type: String,
			default: '#ffffff',
		},
		bgColor: {
			type: String,
			default: '#666666',
		},
		bgSrc: {
			type: String,
			default: '',
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		prizeName: {
			type: String,
		},
	},
	emits: ['open', 'ready'],
	computed: {
		myCanvasId() {
			if (!this.canvasId) {
				return 'c' + uuid(18);
			} else {
				return this.canvasId;
			}
		},
		scratchCardData(){
			return {
				props:this.$props,
				myCanvasId:this.myCanvasId,
				fun:this.fun
			}
		}
	},
	data() {
		return {
			isDraw: false,
			isShowPrizeName: false,
			fun:0
		};
	},
	methods: {
		async init() {
			this.isShowPrizeName = false;
			// #ifdef MP
			uni.createSelectorQuery()
				.in(this)
				.select('.c-scratch-card')
				.boundingClientRect((res) => {
					this.offsetLeft = res.left;
					this.offsetTop = res.top;
				})
				.exec();
					
			let { canvas, pixelRatio } = await this.getContext();
			this.myCanvas = canvas;
			this.pixelRatio = pixelRatio;
			const ctx = canvas.getContext('2d');
			this.ctx = ctx;
			if (this.bgSrc) {
				let img = await this.loadImg(this.bgSrc);
				ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
				this.ready()
			} else {
				ctx.fillStyle = this.bgColor;
				ctx.fillRect(0, 0, canvas.width, canvas.height);
				ctx.font = `normal 400 ${this.textSize * pixelRatio}px sans-serif`;
				ctx.fillStyle = this.textColor;
				ctx.fillText(this.text, (canvas.width - ctx.measureText(this.text).width) / 2, canvas.height / 2);
				this.ready()
			}
			// #endif
			// #ifndef MP
			this.fun++
			// #endif
			
		},
		// #ifdef MP
		getContext() {
			return new Promise((resolve) => {
				const { pixelRatio } = uni.getSystemInfoSync();
				uni.createSelectorQuery()
					.in(this)
					.select(`#${this.myCanvasId}`)
					.fields({ node: true, size: true })
					.exec((res) => {
						const { width, height } = res[0];
						const canvas = res[0].node;
						canvas.width = res[0].width * pixelRatio;
						canvas.height = res[0].height * pixelRatio;
						resolve({ canvas, width, height, pixelRatio });
					});
			});
		},
		loadImg(src) {
			return new Promise((resolve, reject) => {
				let imgBit = this.myCanvas.createImage();
				imgBit.src = src;
				imgBit.onload = (e) => {
					resolve(imgBit);
				};
			});
		},
		
		ontouchstart() {
			if (!this.disabled) this.isDraw = true;
		},
		ontouchmove(e) {
			if (this.isDraw) {
				let x = e.changedTouches[0].x * this.pixelRatio;
				let y = e.changedTouches[0].y * this.pixelRatio;
				this.ctx.globalCompositeOperation = 'destination-out';
				this.ctx.beginPath();
				this.ctx.arc(x, y, this.lineWidth * this.pixelRatio, 0, 2 * Math.PI);
				this.ctx.fill();
			}
		},
		ontouchend() {
			this.isDraw = false;
			// 得到canvas的全部数据
			let x = 0,
				y = 0;
			let a = this.ctx.getImageData(x, y, this.myCanvas.width, this.myCanvas.height);
			// ctx.putImageData(a,0,0);
			let j = 0;
			for (let i = 3; i < a.data.length; i += 4) { 
				if (a.data[i] == 0) j++;
			}
			// 当被刮开的区域等于一半时，则可以开始处理结果
			if (j >= a.data.length / 8) {
				this.open()
			}
		},
		// #endif
		open(){
			this.$emit('open');
		},
		ready(){
			this.$emit('ready');
			this.isShowPrizeName = true;
		}
	},
	mounted() {
		// #ifdef MP
			this.init();
		// #endif
	},
};
</script>
<!-- #ifndef MP -->
	
	<!-- #ifdef VUE3 -->
	<script lang="renderjs" src='./js/render.js' module='scratchCard'></script>
	<!-- #endif -->
	
	<!-- #ifdef VUE2 -->
	<script lang="renderjs" module='scratchCard'>
		import lottieRender from "./js/render.js"
		export default {
			mixins:[lottieRender],
		}
	</script>
	<!-- #endif -->
<!-- #endif -->

<style lang="scss" scoped>
.c-scratch-card {
	// width: v-bind(width);
	// height: v-bind(height);
	position: relative;
	/* #ifndef MP */
	div {
		width: 100%;
		height: 100%;
	}
	/* #endif */

	.canvas {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
}
.prizeName {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100%;
}
</style>
